from datetime import datetime, timedelta
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from auth.auth_jwt import generic_token
from toutiao import Config


# def get_token(user_id):
#     # 1.创建序列号器   后面2个参数,一个是秘钥,一个是时间
#     s = Serializer(secret_key=Config.SECRET, expires_in=Config.TOKEN_EXPIRY)
#     # 2 组织数据
#     data = {
#         'user_id': user_id
#     }
#     # 3.生成token
#     return s.dumps(data).decode()

# -----------------上面这个token生成安全度不足,并且不能满足需求------------------


def get_token(user_id):
    # 1. 获取当前的时间
    now = datetime.utcnow()

    # 2. 分别组织 token 和 refresh_token的payload数据
    token_pay = {'refresh': False, 'user_id': user_id}
    refresh_pay = {'refresh': True, 'user_id': user_id}

    # 3. 分别组织 token 和 refresh_token的expiry时间
    token_exp = now + timedelta(hours=Config.JWT_EXPIRY_HOURS)
    refresh_exp = now + timedelta(days=Config.JWT_REFRESH_DAYS)

    # 4. 生成2个不同的token
    # 2个小时有效期
    token = generic_token(token_pay, token_exp)
    # 14天有效期
    refresh_token = generic_token(refresh_pay, refresh_exp)
    return token, refresh_token
